class SavedCart < ActiveRecord::Base
  belongs_to :client
  belongs_to :product
  belongs_to :product_color

=begin
  def self.get(client_id)
    elements = SavedCart.where(:client_id => client_id)

    if !elements.blank?
      elements
    else
      SavedCart.new(:client_id => client_id)
    end
  end
=end

  def self.has_saved_items(client_id)
    elements = SavedCart.where(:client_id => client_id)

    if !elements.blank?
      true
    else
      false
    end
  end

  def self.add_item(client_id, item)
    begin
      sc = SavedCart.new(
          :client_id => client_id,
          :product_id => item.product_id,
          :product_color_id => item.color_id,
          :quantity => item.quantity
      )

      sc.save
    rescue

    end
  end

  def self.remove_item(client_id, item)
    begin
      sc = SavedCart.where(
          :client_id => client_id,
          :product_id => item.product_id,
          :product_color_id => item.color_id
      )

      if !sc.blank?
        sc.first.delete
      end
    rescue

    end
  end

  def self.empty_cart(client_id)
    begin
      sc = SavedCart.where(:client_id => client_id)

      if !sc.blank?
        sc.delete_all
      end
    rescue

    end
  end

  def self.update_item(client_id, item, final_quantity = false)
    begin
      sc = SavedCart.where(
          :client_id => client_id,
          :product_id => item.product_id,
          :product_color_id => item.color_id
      )

      if !sc.blank?
        saved_item = sc.first

        if final_quantity
          quantity = item.quantity
        else
          quantity = saved_item.quantity + item.quantity
        end

        saved_item.update_attribute(:quantity, quantity)
      end
    rescue

    end
  end
end
